package cn.jinjimi.app.main.activity;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.controller.event.LoginSuccessEvent;
import cn.jinjimi.app.controller.event.ResetPasswordEvent;
import cn.jinjimi.app.main.extend.ToolBarCommonActivity;
import cn.jinjimi.app.main.fragment.LoginFragment;
import cn.jinjimi.app.util.AppUtils;
import cn.jinjimi.framework.router.RouterHelper;

/**
 * A login screen that offers login via mobile/password.
 * @author zhenhua
 */
public class LoginActivity extends ToolBarCommonActivity {
    public static String loginFrom;

    @Override
    protected void beforeInitView() {
        setContentView(R.layout.activity_login);
    }

    @Override
    protected void initial() {
        initView();
    }

    protected void initView() {
        final FragmentManager fm = this.getSupportFragmentManager();
        fm.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {

            }
        });
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.content_fragment, new LoginFragment(), "LOGIN");
        ft.commit();
    }

    @Override
    protected void rightAction() {
        super.rightAction();
    }

    @Override
    public void onBackPressed() {
        if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
            try {
                getSupportFragmentManager().popBackStack();
            } catch (IllegalStateException e) {
                //
            }
        } else {
            if (!isTaskRoot()) {
                finish();
            } else {
                RouterHelper.toUrl(this, Constants.Route.HOME_URL);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginSuccessEvent(LoginSuccessEvent event) {
        AppUtils.onLoginStateChange(this);
        if (AccountManager.getInstance().isLogin()) {
            setResult(RESULT_OK);
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onResetPasswordEvent(ResetPasswordEvent event) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        loginFrom = null;
    }

    public static void setLoginFrom(String loginFrom) {
        LoginActivity.loginFrom = loginFrom;
    }

    public static String getLoginFrom() {
        return loginFrom;
    }
}